package com.mihu.stmall.manager.mapper;

import com.mihu.stmall.manager.entiy.Category;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * Mapper层接口
 * 基于注解的开发
 */
@Mapper  //MyBatis的注解 当前的接口是MyBatis的接口 相当于Application上添加@MapperScan注解
public interface CategoryMapper {

    /**
     * 插入数据表的操作
     * 1.返回值类型 int
     * 2.方法名 insert
     * 3.参数 Category
     * 4.配置 使用@Insert的注解配置SQL语句
     */
    @Insert({"insert into category",
            "(name,dscp,pic,parent_id,recom)",
            "value(#{name},#{dscp},#{pic},#{parentId},#{recom})",
    })
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    int insert(Category category);

    /**
     * 根据ID删除
     */
    @Delete("delete from category where id=#{id}")
    int delete(Integer id);

    /**
     * 根据ID更新 使用动态SQL,需要为SQL语句添加<script></script>
     */
    @Update({"<script>",
            "update category",
            "<set>",
            "<if test='name != null and name.length>0'>name=#{name},</if>",
            "<if test='dscp != null and dscp.length>0'>dscp=#{dscp},</if>",
            "<if test='pic != null and pic.length>0'>pic=#{pic},</if>",
            // 判断参数category的parentId属性不为空，
            // 设置数据表的parent_id字段为参数category的parentId的属性
            "<if test='parentId != null'>parent_id=#{parentId},</if>",
            "<if test='recom != null'>recom=#{recom}</if>",
            "</set>",
            "where id=#{id}",
            "</script>",
    })
    int update(Category category);

    /**
     * 根据ID查询
     */
    @Select("select * from category where id=#{id}")
    Category selectById(Integer id);

    /**
     * 通用的多条件的组合查询
     */
    @Select({"<script>",
            "select * from category",
            "<where>",
            "<if test='name != null and name.length>0'>name like '%${name}%'</if>",
            "<if test='parentId != null and parentId!=0'> and parent_id = #{parentId} </if>",
            "<if test='parentId != null and parentId==0'> and parent_id is null</if>",
            "<if test='recom != null'> and recom = #{recom} </if>",
            "<if test='status != null'> and status = #{status} </if>",
            "</where>",
            "</script>"
    })

    @Results({   //相当于<resultMap>的标签
            @Result(column = "parent_id",property="parent",
                    one = @One(select = "selectById"))      //相当于<id><result>标签
    })
    List<Category> select(Category category);

}